<template>
  <div style="">
    <Header :left="true" leftText="返回" title="工艺点检扫描"> </Header>
    <div>
      <Form>
        <Field v-model="form.equipName" ref="equipNameFocus" readonly size="large" @keyup.enter.native="afterScan" center
          colon label="设备编码">
          <Icon slot="right-icon" center name="enlarge" size="2em" @click="showScanner"></Icon>
        </Field>
        <Field v-model="form.equipDesc" :readonly="true" size="large" center colon label="设备名称" />
        <Field v-model="form.orderNumber" ref="equipNameFocus" readonly size="large" @keyup.enter.native="afterOrderScan"
          center colon label="工单号">
          <Icon slot="right-icon" center name="enlarge" size="2em" @click="orderScanner"></Icon>
        </Field>
      </Form>

      <!-- <van-button
        color="#ff9933"
        :block="true"
        class="buttonLeft"
        v-show="btnShow"
        type="primary"
        text="取消"
        @click="close"
      />
      <van-button
        color="#1076c0"
        :block="true"
        class="buttonRight"
        v-show="btnShow"
        :hairline="false"
        type="primary"
        :disabled="subButton"
        text="保存"
        @click="save"
      /> -->
    </div>
  </div>
</template>

<script>
import {
  Form,
  Cell,
  Icon,
  Field,
  NumberKeyboard,
  Picker,
  popup,
  SubmitBar,
  Divider,
  Button,
  Loading,
  Overlay,
  Dialog,
  Toast,
} from "vant";
import "vue-easytable/libs/themes-base/index.css";
import { VTable } from "vue-easytable";
import { _httpClient } from "@/libs/api";
import { getToken, getBaseApiFrefix } from "@/libs/auth";
import Header from "@/components/header.vue";
import { storage } from "@/libs/utils";
Vue.use(Overlay);
Vue.use(Loading);
Vue.use(Button);
Vue.use(Divider);
Vue.use(Picker);
Vue.use(popup);
Vue.use(SubmitBar);

export default {
  name: "qualityInspection",
  components: {
    Header,
    Form,
    Cell,
    Icon,
    Field,
    NumberKeyboard,
    VTable,
    Dialog,
    Toast,
  },
  data: function () {
    return {
      btnShow: true,
      subButton: true, //提交按钮默认状态
      sourceShowPicker: false,
      reasonTemp: null, //原因
      form: {
        user: null,
        type: "2", //生产1物流2质量3
        siteKey: null,
        eqKey: null,
        equipName: null, //设备编码
        equipDesc: null, //设备名称
        orderNumber: null, //工单号
      },
      columns: [],
      pickListMap: new Map(),
      user: {}, //登录用户信息
    };
  },
  //页面初始化监听事件
  created: function () {
    this.user = JSON.parse(storage.get("user"));
    this.form.siteKey = this.user.site;
    api.requestPermission(
      {
        list: ["camera", "microphone", "storage"],
      },
      function (ret, err) { }
    );

    try {
      var manageStorage = api.require("manageStorage");
      manageStorage.getDeviceVersion({}, function (rett) {
        if (Number(rett.version) >= 30) {
          manageStorage.hasAllFilePermission({}, function (ret) {
            if (ret.status == true) {
              return;
            } else {
              manageStorage.requestAllFilePermission({}, function (ret) {});
            }
          });
        } else {
          return;
        }
      });
    } catch {}
    
    this.showScanner();
  },
  //页面初始化完成监听事件
  mounted: function () {
    const oldHight = api.winHeight;
    addEventListener("resize", () => {
      let newHight = api.winHeight;
      this.btnShow = newHight < oldHight ? false : true;
    });
  },
  methods: {
    //打开扫描
    showScanner() {
      let _this = this;
      if (
        api.deviceName.toLowerCase() == "huawei" ||
        api.deviceName.toLowerCase() == "honor"
      ) {


        var zyHmsScan = api.require('zyHmsScan');
        var param = {
          //returnAll:true
        };
        zyHmsScan.openDefaultView(param, function (ret) {
          _this.form.equipName = ret.result;
          _this.afterScan();

          //api.alert({ msg: JSON.stringify(ret) });
        });
        // var QRScan = api.require("QRScan");
        // QRScan.customizedScanner(
        //   {
        //     rect: {
        //       x: 15, //（可选项）数字类型；模块左上角的 x 坐标（相对于所属的 Window 或 Frame）；默认：0
        //       y: 0, //（可选项）数字类型；模块左上角的 y 坐标（相对于所属的 Window 或 Frame）；默认：0
        //       w: 320, //（可选项）数字类型；模块的宽度；支持设置'auto'；默认：所属的 Window 或 Frame 的宽度
        //       h: 480, //（可选项）数字类型；模块的高度；支持设置'auto'；默认：所属的 Window 或 Frame 的高度
        //     },
        //     rectOfInterest: {
        //       x: 64, //（可选项）数字类型；扫码识别区域左上角的 x 坐标（相对于扫码区rect）；默认：0
        //       y: 65, //（可选项）数字类型；扫码识别区域左上角的 y 坐标（相对于扫码区rect）；默认：0
        //       w: 250, //（可选项）数字类型；扫码识别区域的宽度；默认：扫码区rect的宽度
        //       h: 250, //（可选项）数字类型；扫码识别区域的高度；默认：扫码区rect的高度
        //     },
        //     //tipString:'放入框内扫码',
        //     maskColor: "rgba(0,0,0,0.5)",
        //     scanLine: {
        //       color: "#00FF00",
        //       thickness: 2,
        //     },
        //     marginB: 30,
        //     formatType: "ALL",
        //   },
        //   function (ret) {
        //     if (ret) {
        //       _this.form.equipName = ret.result;
        //       _this.afterScan();
        //     }
        //   }
        // );
        //    QRScan.closeCustomizedScanner();
      } else {
        var FNScanner = this.$ac.require("FNScanner");
        FNScanner.openScanner(
          {
            autorotation: true,
          },
          function (ret, err) {
            if (ret) {
              if (ret.eventType == "success" && ret.content != "") {
                _this.form.equipName = ret.content;
                _this.afterScan();
              }
            } else {
              alert(JSON.stringify(err));
            }
          }
        );
      }
    },
    //工单扫描
    orderScanner() {
      let _this = this;
      var FNScanner = this.$ac.require("FNScanner");
      FNScanner.openScanner(
        {
          autorotation: true,
        },
        function (ret, err) {
          if (ret) {
            if (ret.eventType == "success" && ret.content != "") {
              _this.form.orderNumber = ret.content;
              _this.afterOrderScan();
            }
          } else {
            alert(JSON.stringify(err));
          }
        }
      );
    },

    async afterScan() {
      let _this = this;
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() +
          "/app/resourcecall/resourceCallInfo/equipDesc",
          {
            body: {
              equipName: _this.form.equipName,
              siteKey: _this.form.siteKey,
            },
          }
        );
        if (res.code === 200) {
          _this.form.eqKey = res.rows[0].eqKey;
          _this.form.equipDesc = res.rows[0].equipDesc;
          _this.form.user = _this.user.nickName;
          _this.form.callUser = _this.user.userName;
          _this.form.callTime = _this.getNowTime();
          if (_this.form.callReason) {
            _this.subButton = false;
          }
        } else {
          Toast.fail(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },

    //扫描工单号后触发操作
    async afterOrderScan() {
      if (this.form.eqKey == null) {
        Toast("请扫描设备条码");
        return;
      }
      if (this.form.orderNumber == null) {
        Toast("请扫描工单条码");
        return;
      }
      let _this = this;
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/equipment/task/checkCraft",
          {
            body: {
              eqKey: _this.form.eqKey,
              orderNumber: _this.form.orderNumber,
              siteKey: _this.user.site,
              department: _this.user.dept.deptName,
            },
          }
        );
        if (res.code === 200) {
          if (res.data.length == 0) {
            //创建新的工艺点检单
            _this.createCraft();
          } else {
            Dialog.confirm({
              title: "提示",
              theme: "round-button",
              message: "当前订单存在点检任务未完成，是否继续完成上次点检任务?",
            })
              .then(() => {
                let data = {
                  body: {
                    taskCode: res.data[0].taskCode,
                    siteKey: _this.user.site,
                    eqStatus: res.data[0].eqStatus,
                    taskType: res.data[0].taskType,
                    equipCode: _this.form.equipName,
                  },
                };
                _this.queryTask(data);
              })
              .catch(() => { });
          }
        } else {
          Toast.fail(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },

    //创建工艺点检任务单
    async createCraft() {
      let _this = this;
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/equipment/task/creatCraft",
          {
            body: {
              eqKey: _this.form.eqKey,
              orderNumber: _this.form.orderNumber,
              siteKey: _this.user.site,
              department: _this.user.dept.deptName,
              equipCode: _this.form.equipName,
            },
          }
        );
        if (res.code === 200) {
          let data = {
            body: {
              taskCode: res.data.taskCode,
              siteKey: res.data.siteKey,
              eqStatus: res.data.eqStatus,
              taskType: res.data.taskType,
              equipCode: res.data.equipCode,
            },
          };
          _this.queryTask(data);
        } else {
          Toast.fail(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },

    //查询任务详情
    async queryTask(data) {
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "请稍等...",
      });
      let that = this;
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/equip/check/isExist",
          data
        );
        Toast.clear();
        if (res.code === 200) {
          if (res.taskItemList.length > 0) {
            //跳转到点检页面
            this.$ac.openWin({
              name: "equip_check",
              url: "./maintain-spotCheck-equip_check.html",
              pageParam: {
                equipCode: data.body.equipCode,
                taskItemList: res.taskItemList,
                taskFileList: res.taskFileList,
              },
            });
            //监听页面返回
            api.addEventListener(
              {
                name: "result",
              },
              function (ret, err) {
                if (
                  ret.value.taskCode != "" &&
                  ret.value.taskCode != undefined
                ) {
                  that.form.equipName = null;
                  that.form.orderNumber = null;
                  that.form.equipDesc = null;
                  that.form.eqKey = null;
                }
              }
            );
          } else {
            that.$ac.message({
              title: "提示",
              msg: "没有找到设备对应的点检项目，请核实",
            });
          }
        } else {
          Toast.fail(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },

    getNowTime() {
      let today = new Date();
      let month = today.getMonth() + 1;
      month = month < 10 ? "0" + month : month;
      let day = today.getDate() < 10 ? "0" + today.getDate() : today.getDate();
      let hours =
        today.getHours() < 10 ? "0" + today.getHours() : today.getHours();
      let mins =
        today.getMinutes() < 10 ? "0" + today.getMinutes() : today.getMinutes();
      let secs =
        today.getSeconds() < 10 ? "0" + today.getSeconds() : today.getSeconds();
      return (
        today.getFullYear() +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        mins +
        ":" +
        secs
      );
    },

    //下拉框确认确认
    sourceOnConfirm(value) {
      this.sourceShowPicker = false;
      if (value === undefined) {
        return;
      }
      this.form.callReason = value;
      if (this.form.equipDesc) {
        this.subButton = false;
      }
    },
    close() {
      api.closeWin();
    },
    reset() {
      this.subButton = true;
      this.form.equipDesc = null;
      this.form.equipName = null;
      this.form.eqKey = null;
      this.form.callUser = null;
      this.form.callTime = null;
      this.form.callReason = null;
      this.form.user = null;
    },
  },
};
</script>
<style>
body {
  background-color: white;
}

.table-title-class {
  background-color: #304156;
  color: #fff;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.buttonLeft {
  position: fixed;
  bottom: 8px;
  float: left;
  width: 49%;
}

.buttonRight {
  position: fixed;
  bottom: 8px;
  float: right;
  left: 51%;
  width: 49%;
  background-color: #f22028;
  border-color: #f22028;
}
</style>
